/*
 * DCE400服务系统 -- 后端服务接口 -- 数据访问层 -- 客户数据访问
 * 包括：客户数据库增删改查
 *      客户登录记录插入、查找
 */
package dao

import (
	"errors"
	"fmt"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server_attence/app/entity"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server_attence/app/global"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/db"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/util"
	"go.uber.org/zap"
	"strconv"
	"strings"
	"time"
)

//********************************************
//Func  ：查询数据库：客户列表，分页查询。
//   如果pageSize<=0,则一次性查询全部。
//   如果deptId<=0，则未指明具体部门，查询所有
//Method：GET
//Usage ：
//********************************************
func QueryEmployeeList(page, pageSize int, mobile string, deptId []int64, status int, role int) (int64, []*entity.Employee, error) {
	offset := (page - 1) * pageSize
	session := db.Session().Table("employee")

	defer session.Close()
	if mobile != "" {
		session = session.And("mobile=?", mobile)
	}

	if len(deptId) > 0 { //部门
		var deptSql string
		for _, deptId := range deptId {
			if len(deptSql) > 0 {
				deptSql += " or "
			}
			deptSql += fmt.Sprintf(" %s=%s ", "dept_id", strconv.FormatInt(deptId, 10))
		}
		session = session.And(deptSql)
	}

	if status >= entity.EApplicationStatus_Draft && status <= entity.EApplicationStatus_Pass {
		session = session.And("status=?", status) //筛选状态
	}
	if role >= entity.EEmployeeRole_Outsourcing && role <= entity.EEmployeeRole_Hr {
		session = session.And("role=?", role) //筛选角色
	}

	if role == entity.EEmployeeRole_Undef {
		session = session.And("role=? or role=?", entity.EEmployeeRole_Outsourcing, entity.EEmployeeRole_DeptLeader) //筛选角色
	}

	if pageSize > 0 {
		session.Limit(pageSize, offset)
	}
	users := []*entity.Employee{}
	total, err := session.Omit("password").FindAndCount(&users)
	if err != nil {
		return 0, nil, err
	}
	return total, users, nil
}

//输出map[id]emplyee
func GetAllEmployeeMap() map[int64]*entity.Employee {
	outputMap := make(map[int64]*entity.Employee)

	session := db.Session().Table("employee")
	defer session.Close()
	users := []*entity.Employee{}
	_, err := session.Omit("password").FindAndCount(&users)
	if err != nil {
		return nil
	}
	for _, user := range users {
		outputMap[user.Id] = user
	}
	return outputMap
}

//********************************************
//Func  ：查询数据库：指定客户的详情
//Method：GET
//Param：Id 或 mobile
//Usage ：
//********************************************
func QueryEmployeeDetail(mobile string, id int64) (*entity.Employee, error) {
	session := db.Session().Table("employee") //.Where("id=?",operatorId).Get(&operator)
	defer session.Close()

	if id > 0 {
		session = session.Where("id=?", id)
	}
	if mobile != "" {
		session = session.Where("mobile=?", mobile)
	}
	var user entity.Employee
	has, err := session.Get(&user)
	if err != nil || has == false {
		return nil, err
	}
	return &user, nil
}

//********************************************
//Func  ：添加新操作员（使用手机号作为唯一ID）
//Method：POST
//Usage ：
//********************************************
func InsertEmployee(employee entity.Employee) (*entity.Employee, error) {
	var err error
	if len(strings.TrimSpace(employee.Name)) <= 0 { //姓名（必填）/单位名称
		return nil, errors.New("name is none")
	}

	if len(strings.TrimSpace(employee.Mobile)) <= 0 { //手机（必填）
		return nil, errors.New("mobile is none")
	}

	if len(strings.TrimSpace(employee.Password)) <= 0 { //密码（必填）
		return nil, errors.New("password is none")
	}
	/*
		if employee.DeptId <= 0 { //部门（必填）
			return nil, errors.New("department id is none")
		}

		if employee.LeaderId <= 0 { //领导（必填）
			return nil, errors.New("leader id is none")
		}
	*/
	if employee.Role < entity.EEmployeeRole_Outsourcing || employee.Role > entity.EEmployeeRole_Hr {
		return nil, errors.New("unknow employee role")
	}

	employee.CreatedAt = time.Now()
	employee.UpdateAt = employee.CreatedAt
	employee.Status = entity.EEmployeeStatus_Normal
	employee.Id = util.GenSnowflakeInt64()
	global.Log.Info("InsertEmployee: ", zap.Any("employee:", employee))

	session := db.Session().Table("employee")
	defer session.Close()

	err = session.Begin()
	if err != nil {
		return nil, errors.New("db session begin failed.")
	}

	_, err = session.Insert(&employee) //插入
	if err != nil {
		session.Rollback()
		return nil, err
	}
	err = session.Commit()
	if err != nil {
		return nil, err
	}
	return &employee, nil
}

//********************************************
//Func  ：更新Employee信息
//Method：POST
//Usage ：
//********************************************
func UpdateEmployee(employee entity.Employee, cols string) error {
	var err error
	if len(strings.TrimSpace(employee.Name)) <= 0 { //姓名（必填）/单位名称
		return errors.New("name is none")
	}
	if len(strings.TrimSpace(employee.Mobile)) <= 0 { //手机（必填）
		return errors.New("mobile is none")
	}

	session := db.Session().Table("employee")
	defer session.Close()

	err = session.Begin()
	if err != nil {
		return err
	}

	if len(cols) > 0 {
		_, err = session.Where("id=?", employee.Id).Cols(cols).Update(employee) //更新
	} else {
		_, err = session.Where("id=?", employee.Id).
			Cols("name,mobile,email,dept_id,leader_id,update_at,status,vendor,work_start,work_end").
			Update(employee) //更新
	}

	if err != nil {
		return err
	}
	err = session.Commit()
	if err != nil {
		return err
	}
	return nil
}

//********************************************
//Func  ：Customer删除
//Method：DELETE
//Usage ：客户-账号删除--物理删
//********************************************
func DeleteEmployee(mobile string, id int64) error {
	if mobile == "" && id <= 0 {
		return errors.New("未指定员工信息")
	}

	session := db.Session().Table("employee")
	defer session.Close()

	if id > 0 {
		session = session.And("id=?", id)
	}
	if mobile != "" {
		session = session.And("mobile=?", mobile)
	}
	var customer entity.Employee
	customer.Id = id
	customer.Mobile = mobile
	session.Begin()
	cnt, err := session.Delete(&customer)
	if err != nil {
		session.Rollback()
		return err
	}
	if cnt <= 0 {
		session.Rollback()
		return errors.New("移除用户数量0")
	}
	err = session.Commit()
	return err
}

//********************************************
//Func  ：更新客户手机号
//Method：POST
//Usage ：操作员设置-绑定手机
//********************************************
func UpdateEmployeeMobile(mobile string, id int64, newMobile string) error {
	var err error
	if len(strings.TrimSpace(mobile)) <= 0 {
		return errors.New("mobile is none")
	}
	if len(strings.TrimSpace(newMobile)) <= 0 { //新手机（必填）
		return errors.New("new mobile is none")
	}
	if id <= 0 {
		return errors.New("id is none")
	}

	session := db.Session().Table("employee")
	defer session.Close()
	if id > 0 {
		session = session.Where("id=?", id)
	}
	if mobile != "" {
		session = session.Where("mobile=?", mobile)
	}

	var customer entity.Employee
	customer.Mobile = newMobile

	err = session.Begin()
	if err != nil {
		return err
	}

	_, err = session.Cols("mobile").Update(customer)
	if err != nil {
		session.Rollback()
		return err
	}
	err = session.Commit()
	return err
}

//********************************************
//Func  ：修改密码
//Method：POST
//Usage ：
//********************************************
func UpdateEmployeePassword(mobile string, id int64, pwdSum string) error {
	var err error
	if len(strings.TrimSpace(mobile)) <= 0 && id <= 0 {
		return errors.New("mobile of id is none")
	}
	if len(strings.TrimSpace(pwdSum)) <= 0 { //PASSWORD
		return errors.New("new mobile is none")
	}
	if id <= 0 {
		return errors.New("custom id is none")
	}

	session := db.Session().Table("employee")
	defer session.Close()
	if id > 0 {
		session = session.Where("id=?", id)
	}
	if mobile != "" {
		session = session.Where("mobile=?", mobile)
	}

	var customer entity.Customer
	customer.Password = pwdSum

	err = session.Begin()
	if err != nil {
		return err
	}

	_, err = session.Cols("password").Update(customer)
	if err != nil {
		session.Rollback()
		return err
	}
	err = session.Commit()
	return err
}
